package com.ruoyi.outpatient.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.PersonConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.OSSEntity;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.https.HttpUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.outpatient.core.LoginPatient;
import com.ruoyi.outpatient.core.SecurityUtils;
import com.ruoyi.outpatient.domain.Blog;
import com.ruoyi.outpatient.domain.Person;
import com.ruoyi.outpatient.mapper.IBlogMapper;
import com.ruoyi.outpatient.mapper.IPersonLoginMapper;
import com.ruoyi.outpatient.service.IPersonService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 伟峰
 * @date 2022/5/4
 * @description:
 */
@Service
public class PersonServiceImpl implements IPersonService {

    @Autowired
    private IPersonLoginMapper personMapper;

    @Autowired
    private IBlogMapper blogMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SecurityUtils securityUtils;

    @Value("${url.images}")
    private String URLHeader;

    /**
     * 通过personId查询个人信息
     * @param personId
     * @return person
     */
    @Override
    public AjaxResult selectMyInformation(Long personId) {

        Long loginPersonId = securityUtils.getLoginPersonId();

//        统计个人访问页的 浏览量
        redisCache.setCacheHyperLogLog("statistics:personPageView:"+personId,loginPersonId);

//        1.先查询redis
        Map<String, Object> cacheMap = redisCache.getCacheMap(PersonConstants.PERSON_INFORMATION + personId);


        //        2.redis存储则返回
        if (cacheMap.size()!=0){
            return AjaxResult.success().put("map",cacheMap);
        }
//        3.不存在,则查询数据库
        Person person=personMapper.selectMyInformation(personId);
        int fansSum=personMapper.selectFansSum(personId);
        int followSum=personMapper.selectFollowSum(personId);


//        4.不存在则返回
        if (StringUtils.isNull(person)){
            return AjaxResult.error();}

//        5.数据库存在则添加redis
        Map<String, Object> map = BeanUtil.beanToMap(person);
        map.put("fansSum",fansSum);
        map.put("followSum",followSum);
        redisCache.setCacheMap(PersonConstants.PERSON_INFORMATION+personId,map);
        redisCache.expire(PersonConstants.PERSON_INFORMATION+personId, Constants.INFORMATION_EXPIRATION, TimeUnit.DAYS);
//        6.然后数据库返回
        return AjaxResult.success().put("person",map);
    }

    /**
     * 通过personId查询个人分享文章 按时间排序
     * @param personId
     * @return person
     */
    @Override
    public AjaxResult selectMyBlogList(Long personId) {



//        通过个人id查询个人文章列表 创建时间排序
        List<Blog> blogs= blogMapper.selectMyBlogList(personId);
        for (Blog b:blogs){
            if (b.getBlogImage()!=null)
            {
                String[] split = b.getBlogImage().split("\\^");
                b.setBlogImage(split[0]);
            }
//            String substring = b.getBlogImage().substring(0, b.getBlogImage().indexOf('^'));
//            b.setBlogImage(substring);
        }
        return AjaxResult.success().put("blog",blogs);
    }

    /**
     * 更新用户信息
     * @param person
     * @return
     */
    @Override
    @Transactional  //加上事务防止有一个更新出错
    public AjaxResult informationUpdate(Person person) {
//        redis的更新策略：先更新数据库 在删除缓存

        Long loginPersonId = securityUtils.getLoginPersonId();
        person.setPersonId(loginPersonId);
//        1.更新数据库
        personMapper.informationUpdate(person);

//        2.删除缓存
        redisCache.deleteObject(PersonConstants.PERSON_INFORMATION+person.getPersonId());

        return AjaxResult.success("更新成功");
    }

    /**
     * 用户签到实现
     * @return void
     */
    @Override
    public AjaxResult insertSign() {


//        1.获取用户id
        LoginPatient principal =(LoginPatient) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

//        2.获取当前日期月份yyyy-dd
        String dates = DateUtils.getDates();


//        3.拼接key为了获取 bigmap
       String key= principal.getPerson().getPersonId()+":"+ dates;
//        4.获取今天是第几天，来存入bigmap
        LocalDate now = LocalDate.now();
        int day = now.getDayOfMonth(); //获取当日是几号

//     5.存储到bigmap   key：(用户ID：2022-03)  value:12号 true
        redisCache.setBig(key,day,true);

        return AjaxResult.success();

    }

    /**
     * 获取短信验证码
     * @param phonenumber 手机号
     * @return 短信验证码
     */
    @Override
    public AjaxResult selectVerification(String phonenumber) {


//        1.生成6位随机数字
        String verify = RandomUtil.randomNumbers(6);
//        2.为验证码设置失效时间(为了防止超过60秒重复发送验证码).存redis
        redisCache.setCacheObject(PersonConstants.LOGIN_PHONE + phonenumber, verify, 5, TimeUnit.MINUTES);
//        这个键5分钟过期
        redisCache.setCacheObject(PersonConstants.LOGIN_VERIFY+verify,System.currentTimeMillis(),5,TimeUnit.MINUTES);




        String host = "https://dfsns.market.alicloudapi.com"; //给阿里云客户发需要短信请求
        String path = "/data/send_sms";
        String method = "POST";  //以上三个是发送给短信客服的方式
        String appcode = "1c2ce6d313204d4bb0d59fb45059c8c5"; //AppCode
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        //   bodys.put("content", "code:33333"); //我们生成的验证码
        //     bodys.put("phone_number", "13192527463"); //用户的手机号
        bodys.put("content", "code:"+verify);
        bodys.put("phone_number", phonenumber);
        bodys.put("template_id", "TPL_0000");  //短信模板,可以让客服修改



//        信息准备好后,发送到阿里云客服
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }


//        生成验证码后,如果用户之前不存在了就insert入数据库基本信息
//        if (StringUtils.isNull(personLoginMapper.selectPersion(phonenumber))) {
////            Person person = new Person();
////            person.setPersonName(RandomUtil.randomString(6));
////            person.setPhonenumber(phonenumber);
////            person.setPhonenumberPassword(SecurityUtils.encryptPassword("123456"));
////            personLoginMapper.insertPerson(person);
////        }


      return   AjaxResult.success("请进行登录").put("verify", verify);

    }



    /**
     * 对我blog进行点赞和收藏的人
     * @return
     */
    @Override
    public AjaxResult selectLikeAndCollect() {






        return null;
    }

    /**
     * 通过关键字搜索用户列表
     * @param tagName
     * @return
     */
    @Override
    public AjaxResult selectPersonListByTagName(String tagName) {

       List<Person> personList= personMapper.selectPersonListByTagName(tagName);


       return AjaxResult.success().put("personList",personList);
    }






    @Override
    public AjaxResult selectMyCollectList(Long loginPersonId) {
//        通过个人id查询个人文章列表 创建时间排序
        List<Blog> blogs= blogMapper.selectMyCollectList(loginPersonId);
        for (Blog b:blogs){
            if (b.getBlogImage()!=null)
            {
                String[] split = b.getBlogImage().split("\\^");
                b.setBlogImage(split[0]);
            }
        }
        return AjaxResult.success().put("blog",blogs);
    }


}
